package base;

import java.util.LinkedList;

public class Server
{
	public int					id;
	public int					process_power;
	public LinkedList<Element>	list;
	public int					times_empty_server		= 0;
	public int					times_proceed_server	= 0;

	public Server(int id, int process_power)
	{
		this.id = id;
		this.process_power = process_power;
		list = new LinkedList<Element>();
	}

	/**
	 * Add an element at the end of this server list, and set the el.id_server
	 * to this correspondant id server.
	 * 
	 * @param el the Element to add.
	 */
	public void add(Element el)
	{
		list.add(el);
		el.setIdServer(id);
	}

	public int getId()
	{
		return id;
	}

	public LinkedList<Element> getList()
	{
		return list;
	}

	public int getTimes_empty_server()
	{
		return times_empty_server;
	}

	public int getTimes_proceed_server()
	{
		return times_proceed_server;
	}

	/**
	 * 
	 * @return the total weight from this Server.
	 */
	public int getWeight()
	{
		int weight = 0;
		for (Element el : list)
		{
			weight += el.getWeight();
		}
		return weight;
	}

	/**
	 * Add time+1 to all Element in this server.
	 */
	public void incElementTime()
	{
		for (Element el : list)
		{
			el.setTimeServer(el.time_server + 1);
		}
	}

	public boolean isEmpty()
	{
		return list.isEmpty();
	}

	/**
	 * Operation depending on the Element weight. Also remove the Element if
	 * this server finished to proceed his weight.
	 * 
	 */
	public LinkedList<Element> proceed()
	{
		int power_left = process_power;
		Element el;
		LinkedList<Element> list_element = new LinkedList<Element>();

		while (power_left > 0)
		{
			try
			{
				el = list.getFirst();
				times_proceed_server++;
				power_left = power_left - el.getWeight();
				if (power_left >= 0)
				{
					list_element.add(el);
					list.removeFirst();
				}
				else
				{
					el.setWeight(-power_left);
				}
			}
			catch (Exception noSuchElemException)
			{
				times_empty_server++;
				break;
			}
		}
		return list_element;
	}

	public int size()
	{
		return list.size();
	}
}
